package cn.lyjuan.dwz_manage.demo.config;

import cn.lyjuan.dwz_manage.core.config.*;
import cn.lyjuan.dwz_manage.core.java.filter.LoginCodeFilter;
import cn.lyjuan.dwz_manage.core.java.filter.RequestAttributesFilter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

/**
 * Created by chad on 2016/7/28.
 */
public class ThisWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    /**
     * 加载CstConfig、DBConfig、SecurityConfig<br />
     * 加载自已的配置，只要加进去就可以
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return new Class<?>[]{CstConfig.class, RootConfig.class, DBConfig.class, WebConfig.class, MethodSecurityConfig.class, SecurityConfig.class};
    }

    /**
     * 加载登陆验证码Filter和SpringSecurity的Filter
     * @param servletContext
     * @throws ServletException
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException
    {
        super.onStartup(servletContext);

        // 处理登陆验证码，顺序必须在SpringSecurity前
        FilterRegistration.Dynamic filter = servletContext.addFilter("loginCodeFilter", new LoginCodeFilter());
        filter.addMappingForUrlPatterns(null, false, LoginCodeFilter.FILTER_URL);
        // 启动Spring Security
        filter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
        filter.addMappingForUrlPatterns(null, false, "*.hx");
    }

    /**
     * 加载WebConfig配置
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        return new Class<?>[0];
    }

    /**
     * 设置Servlet拦截的URL匹配条件
     * @return
     */
    @Override
    protected String[] getServletMappings()
    {
        return new String[]{"*.hx"};
    }

    /**
     * 设置全局的Filter
     * @return
     */
    @Override
    protected Filter[] getServletFilters()
    {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        RequestAttributesFilter requestAttributesFilter = new RequestAttributesFilter();

        Filter[] filters = {characterEncodingFilter, requestAttributesFilter};

        return filters;
    }
}
